package base.copy;

import java.io.*;

/**
 * @author liweimin
 * @date 2021/5/29 11:34
 * @since
 */
public class DeepCopy2 {

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Age a = new Age(20);
        Student stu1 = new Student("摇头耶稣", a, 175);
        //通过序列化方法实现深拷贝
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);

        //写入对象流
        oos.writeObject(stu1);
        oos.flush();

        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));

        Student student = (Student) ois.readObject();

        System.out.println(stu1);
        System.out.println(student);

        System.out.println(student.hashCode());
        System.out.println(stu1.hashCode());

        System.out.println("========================= 修改stu1的属性 =========================");

        stu1.setLength(123);
        stu1.setName("李二狗");
        a.setAge(456);

        System.out.println(stu1);
        System.out.println(student);

        System.out.println(student.hashCode());
        System.out.println(stu1.hashCode());

    }

    static class Student implements Serializable {


        //学生类的成员变量（属性）,其中一个属性为类的对象
        private String name;
        private Age aage;
        private int length;

        //构造方法,其中一个参数为另一个类的对象
        public Student(String name, Age a, int length) {
            this.name = name;
            this.aage = a;
            this.length = length;
        }


        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Age getaAge() {
            return this.aage;
        }

        public void setaAge(Age age) {
            this.aage = age;
        }

        public int getLength() {
            return this.length;
        }

        public void setLength(int length) {
            this.length = length;
        }

        //设置输出的字符串形式
        @Override
        public String toString() {
            return "姓名是： " + this.getName() + "， 年龄为： " + this.getaAge().toString() + ", 长度是： " + this.getLength();
        }


    }

    static class Age implements Serializable {
        //年龄类的成员变量（属性）
        private int age;

        //构造方法
        public Age(int age) {
            this.age = age;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return this.age + "";
        }

    }
}
